import React from "react";
export default class BindThis extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg: "default msg",
    };
    // 绑定this 传递参数方式2
    //   bind改变了this指向后，返回值是被改变this指向后的函数的引用
    //   bind不会修改原函数的this指向,修改后的值重复赋值给原函数
    this.changeMsg2 = this.changeMsg2.bind(this);
  }
  render() {
    return (
      <div>
        <h1>绑定this--传参的几种方式</h1>
        <button onClick={this.changeMsg1.bind(this, "yo", "hua")}>
          绑定this传参方式1
        </button>
        <button onClick={this.changeMsg2}>绑定this传参方式2</button>
        <button onClick={() => this.changeMsg3()}>绑定this传参方式3</button>
        <hr />
        <h3>{this.state.msg}</h3>
        <input
          ref="input"
          type="text"
          style={{ width: "50%" }}
          value={this.state.msg}
          onChange={() => {
            this.updataMsg();
          }}
          //   readOnly
        />
      </div>
    );
  }
  //   changeMsg1 = () => {
  //     //   此时this指向 undefined
  //     console.log(this);
  //     this.setState({
  //       msg: "123",
  //     });
  //   };
  changeMsg1(arg1, arg2) {
    this.setState({
      msg: "123" + arg1 + arg2,
    });
  }
  changeMsg2() {
    this.setState({
      msg: "456",
    });
  }
  changeMsg3() {
    this.setState({
      msg: "789",
    });
  }
  updataMsg() {
    console.log(this.refs.input.value);
    this.setState({
      msg: this.refs.input.value,
    });
  }
}
